package com.hzw.saas.web.admin.config;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.hzw.saas.common.config.util.PageParam;
import lombok.Data;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description
 * @Date 2021/7/7 1:25 下午
 * @Created by sonam
 */
@RestControllerAdvice
public class ResponseResultHandler implements ResponseBodyAdvice<Object> {

    @Data
    private class Page extends PageParam {
        private List records = new ArrayList();
    }

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if(body instanceof IPage) {
            IPage<?> iPage = (IPage<?>) body;
            Page page = new Page();
            page.setCurrent(iPage.getCurrent());
            page.setSearchCount(iPage.isSearchCount());
            page.setSize(iPage.getSize());
            page.setTotal(iPage.getTotal());
            page.setRecords(iPage.getRecords());
            return page;
        }
        return body;
    }

}
